package com.example.vueblog.config;

import com.example.vueblog.common.Result;
import com.example.vueblog.common.enums.ResultEnum;
import com.example.vueblog.common.execption.BaseException;
import com.example.vueblog.common.execption.LoginVerifyException;
import com.example.vueblog.common.execption.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 *
 * @author yushunshun
 * @date 2022/5/29 0:04
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {


    /**
     * 断言空异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<?> handleAssertException(IllegalArgumentException e) {
        return Result.error(e.getMessage());
    }

    /**
     * 校验
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result<?> handleAssertException(BaseException e) {
        return Result.error(e.getCode(), e.getMessage());
    }


    /**
     * 参数非法（效验参数）异常 MethodArgumentNotValidException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    //@ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleValidException(MethodArgumentNotValidException e) {
        log.error("数据效验出现问题{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return Result.error(ResultEnum.VAILD_EXCEPTION.getCode(), ResultEnum.VAILD_EXCEPTION.getMessage(), null);
    }


    /**
     * 最大异常统一返回处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public Result<?> handleException(ServiceException e) {
        return Result.error(ResultEnum.FAILURE.getMessage());
    }
}
